package com.leyou.auth.config;

import com.leyou.auth.utils.RsaUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author CHERRY
 * @date 2018-09-16-16:33
 */
@ConfigurationProperties(prefix = "leyou.jwt")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class JwtProperties {

    /**
     * 密钥
     */
    private String secret;

    /**
     * 公钥
     */
    private String pubKeyPath;

    /**
     * 私钥
     */
    private String priKeyPath;

    /**
     * token 过期时间
     */
    private int expire;

    /**
     * 公钥
     */
    private PublicKey publicKey;

    /**
     * 私钥
     */
    private PrivateKey privateKey;

    /**
     * 保存到cookie的名称
     */
    private String cookieName;

    /**
     * cookie保存时间
     */
    private Integer cookieMaxAge;

    private static final Logger LOGGER = LoggerFactory.getLogger(JwtProperties.class);

    /**
     * 构造方法之后执行方法
     */
    @PostConstruct
    public void init() {

        try {
            File priKey = new File(priKeyPath);
            File pubKey = new File(pubKeyPath);

            if (!priKey.exists() || !pubKey.exists()) {
                //生成公钥或私钥
                RsaUtils.generateKey(pubKeyPath, priKeyPath, secret);
            }

            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
        } catch (Exception e) {
            LOGGER.error("获取公钥私钥失败");
            throw new RuntimeException();
        }
    }
}
